<template>
  <div class="app-container">
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      :height="tableHeight"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @row-click="rowClick"
    >
      <el-table-column fixed="left" label="用户名称0" prop="sort" align="center" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.userName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户编码" min-width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.roleName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属部门" min-width="150px" align="center">
        <template>
          <span>{{ departMent }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所在岗位" width="110px" align="center">
        <template slot-scope="scope">
          <el-tag>{{ RoleTypeVals[scope.row.roleType] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="角色" width="110px" align="center">
        <template slot-scope="scope">
          <el-tag>{{ RoleTypeVals[scope.row.roleType] }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="性别" width="150px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" width="110px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.UserCount }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" class-name="status-col" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.isEffective | statusFilter">
            <i v-if="row.isEffective" class="el-icon-check" />
            <i v-else class="el-icon-close" style="right:0" />
            {{ row.isEffective?'有效':'无效' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button v-for="btn in tableBtnData" :key="btn.name" :type="btn.type" size="mini" @click="btnClick(row, btn.name)">
            <font-awesome-icon :icon="btn.icon" fixed-width />{{ btn.name }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :inline="true" class="demo-form-inline" :rules="rules" :model="temp" label-position="right" label-width="120px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="temp.roleName" />
        </el-form-item>
        <el-form-item label="显示顺序">
          <el-input v-model="temp.sort" />
        </el-form-item>
        <el-form-item label="角色分类">
          <el-select v-model="temp.roleType" class="filter-item" placeholder="请选择">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否有效">
          <el-checkbox v-model="temp.isEffective" />
        </el-form-item>
        <el-form-item label="备注说明" class="input-width-full">
          <el-input v-model="temp.memo" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="dialogPvVisible">
      <span slot="title">
        查看角色 -- {{ rowData.roleName }}
      </span>
      <div class="roleState">
        <div class="roleItem">角色分类: <span>{{ RoleTypeVals[rowData.roleType] }}</span></div>
        <div class="roleItem">所属部门: <span>{{ departMent }}</span></div>
        <div class="roleItem">人数: <span>{{ rowData.UserCount }}</span></div>
        <div class="roleItem">状态： <span>{{ rowData.isEffective }}</span></div>
      </div>
      <el-tabs type="border-card">
        <el-tab-pane label="用户管理">
          <el-button v-for="item in GetRoleList.users" :key="item.userName" :type="item.type" size="mini" class="six"><font-awesome-icon :icon="item.icon" size="lg" fixed-width />{{ item.userName }}</el-button>
        </el-tab-pane>
        <el-tab-pane label="配置管理">
          <el-table
            :key="tableDialogKey"
            :data="GetRoleList.moduleBtns"
            :height="250"
            border
            fit
            highlight-current-row
            style="width: 100%;"
            :default-sort="{prop: 'sort', order: 'ascending'}"
          >
            <el-table-column label="模块名称" prop="sort" align="center" width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.moduleName }}</span>
              </template>
            </el-table-column>
            <el-table-column label="按钮权限" min-width="150px" align="center">
              <template slot-scope="scope">
                <el-tag v-for="listItem in scope.row.list" :key="listItem.btnName">{{ listItem.btnName }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogPvVisible = false">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { GetDeptUsers, GetRole, EditRole, AddRole, DeleteRole } from '@/api/system'
import waves from '@/directive/waves' // Waves directive
import * as R from 'ramda'

export default {
  name: 'ComplexTable',
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = status ? 'success' : 'danger'
      return statusMap
    }
  },
  props: {
    tableHeight: {
      type: Number,
      default: 500
    },
    tableBtnData: {
      type: Array,
      default: n => []
    },
    departMent: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tableKey: 0,
      tableDialogKey: 0,
      list: null,
      GetRoleList: {
        moduleBtns: [],
        users: []
      },
      total: 0,
      listLoading: true,
      statusOptions: [{
        value: 9,
        label: '系统管理员'
      },
      {
        value: 1,
        label: '系统角色'
      },
      {
        value: 2,
        label: '业务角色'
      },
      {
        value: 3,
        label: '修改数据角色'
      }],
      showReviewer: false,
      temp: {
        deptID: 1,
        edit: false,
        id: 0,
        isEffective: true,
        isRemove: false,
        memo: '',
        roleName: '',
        roleType: null,
        sort: 0
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '新增'
      },
      dialogPvVisible: false,
      rules: {
        type: [{ required: true, message: 'type is required', trigger: 'change' }],
        roleName: [{ required: true, message: '模块名称不能为空', trigger: 'change' }],
        moduleCode: [{ required: true, message: '模块编码不能为空', trigger: 'change' }],
        timestamp: [{ type: 'date', required: true, message: 'timestamp is required', trigger: 'change' }],
        title: [{ required: true, message: 'title is required', trigger: 'blur' }]
      },
      parentId: 1,
      RoleTypeVals: { 1: '系统角色', 2: '业务角色', 3: '修改数据角色', 9: '系统管理员' },
      rowData: {},
      downloadLoading: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    btnClick(row, name) {
      if (name === '修改') {
        this.handleUpdate(row)
      }
      if (name === '删除') {
        this.handleModifyStatus(row)
      }
      if (name === '查看') {
        this.dialogPvVisible = true
        GetRole(row.id).then(response => {
          this.GetRoleList = response.data
          this.GetRoleList.users.forEach(res => {
            if (res.sex) {
              res.type = 'primary'
              res.icon = ['fa', 'mars']
            } else {
              res.type = 'danger'
              res.icon = ['fa', 'venus']
            }
          })
        })
      }
    },
    getList(parentId = 1) {
      this.listLoading = true
      GetDeptUsers(parentId).then(response => {
        this.list = response.data.map(item => {
          item.edit = false
          return item
        })
        this.total = response.data.length
        this.listLoading = false
        this.parentId = parentId
      })
    },
    handleModifyStatus(row) {
      DeleteRole(row.id).then(response => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        var isEven = n => n.id !== row.id
        this.list = R.filter(isEven)(this.list)
      })
    },
    resetTemp(id) {
      this.temp = {
        deptID: 1,
        edit: false,
        id: 0,
        isEffective: true,
        isRemove: false,
        memo: '',
        roleName: '',
        roleType: null,
        sort: 0
      }
    },
    handleCreate(id) {
      this.resetTemp(id)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempParma = this.temp
          tempParma.deptID = this.parentId
          tempParma.id = 0
          AddRole(tempParma).then(() => {
            this.getList(this.parentId)
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          EditRole(tempData).then(() => {
            for (const v of this.list) {
              if (v.id === this.temp.id) {
                const index = this.list.indexOf(v)
                this.list.splice(index, 1, this.temp)
                break
              }
            }
            this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    handleDelete(row) {
      this.$notify({
        title: '成功',
        message: '删除成功',
        type: 'success',
        duration: 2000
      })
      const index = this.list.indexOf(row)
      this.list.splice(index, 1)
    },
    rowClick(row) {
      console.log(row)
      this.rowData = row
      this.$emit('rowClick', row)
    }
  }
}
</script>

<style>
.app-container {
  height: 100%;
}
.input-width-full {
  display: block;
  width: 100%;
}
.input-width-full .el-form-item__content {
  width: 75%;
}
.roleState {
  display: flex;
  margin-bottom: 10px;
}
.roleState span {
  color: #909399;
}
.roleState > .roleItem {
  color: black;
  font-weight: 600;
  margin-right: 20px;
}
.six {
  margin: 0 5px 5px 10px;
  min-width: 120px;
}
</style>
